package com.hhn.compose

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
                ) {
                    MainNavigationContainer()
                }
            }
        }
    }
}

data class NavItem(
    val title: String, val icon: ImageVector, val badgeCount: Int = 0
)

@SuppressLint("UnrememberedMutableState")
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
fun MainNavigationContainer() {
    // 定义导航项
    val navItems = remember {
        listOf(
            NavItem("首页", Icons.Default.Home),
            NavItem("搜索", Icons.Default.Search, 5),
            NavItem("收藏", Icons.Default.Favorite),
            NavItem("我的", Icons.Default.Person, 99),
            NavItem("设置", Icons.Default.Settings)
        )
    }

    // 分页器状态（用于滑动切换）
    val pagerState = rememberPagerState(pageCount = { navItems.size })
    val coroutineScope = rememberCoroutineScope()

    // 当前选中的索引（用于点击切换）
    val selectedIndex by derivedStateOf { pagerState.currentPage }

    Scaffold(
        bottomBar = {
            NavigationBar(
                containerColor = MaterialTheme.colorScheme.surfaceVariant, tonalElevation = 8.dp
            ) {
                navItems.forEachIndexed { index, item ->
                    NavigationBarItem(
                        icon = {
                        BadgedBox(
                            badge = {
                                if (item.badgeCount > 0) {
                                    Badge {
                                        Text(
                                            text = if (item.badgeCount > 99) "99+"
                                            else item.badgeCount.toString(), fontSize = 10.sp
                                        )
                                    }
                                }
                            }) {
                            Icon(
                                imageVector = item.icon,
                                contentDescription = item.title,
                                modifier = Modifier.size(24.dp)
                            )
                        }
                    },
                        label = { Text(item.title, fontSize = 12.sp) },
                        selected = selectedIndex == index,
                        onClick = {
                            // 点击导航项时平滑滚动到对应页面
                            coroutineScope.launch {
                                pagerState.animateScrollToPage(
                                    page = index, animationSpec = tween(300)
                                )
                            }
                        },
                        alwaysShowLabel = true
                    )
                }
            }
        }) { innerPadding ->
        // 水平分页器实现滑动切换
        HorizontalPager(
            state = pagerState,
            modifier = Modifier
                .padding(innerPadding)
                .fillMaxSize(),
            userScrollEnabled = true
        ) { page ->
            PageContent(
                title = navItems[page].title, pageIndex = page
            )
        }
    }
}

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun PageContent(title: String, pageIndex: Int) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                when (pageIndex % 4) {
                    0 -> Color(0xFFE3F2FD)
                    1 -> Color(0xFFF1F8E9)
                    2 -> Color(0xFFFFF8E1)
                    else -> Color(0xFFFBE9E7)
                }
            ), contentAlignment = Alignment.Center
    ) {
        AnimatedContent(
            targetState = title, transitionSpec = {
                fadeIn(animationSpec = tween(300)) togetherWith fadeOut(animationSpec = tween(300))
            }, label = "PageContentAnimation"
        ) { targetTitle ->
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Text(
                    text = targetTitle,
                    style = MaterialTheme.typography.headlineLarge,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.primary,
                    textAlign = TextAlign.Center
                )

                Spacer(modifier = Modifier.height(20.dp))

                Text(
                    text = "页面内容区域",
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 24.dp)
                )

                Spacer(modifier = Modifier.height(30.dp))

                Box(
                    modifier = Modifier
                        .size(200.dp)
                        .background(
                            color = MaterialTheme.colorScheme.primaryContainer,
                            shape = MaterialTheme.shapes.extraLarge
                        ), contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "页面 ${pageIndex + 1}",
                        style = MaterialTheme.typography.displayMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                }

                Spacer(modifier = Modifier.height(20.dp))

                Text(
                    text = "← 滑动切换页面 →",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 24.dp)
                )
            }
        }
    }
}

@Preview(showBackground = true, showSystemUi = true)
@Composable
fun PreviewMainNavigationContainer() {
    MaterialTheme {
        MainNavigationContainer()
    }
}